#!/usr/bin/env python3
# -*- coding: utf-8 -*-


# base64
# import base64


# s = b"centos6.3"

# bs = base64.b64encode(s)

# print(bs.decode("utf-8"))
# print(base64.b64encode("centos6.3".encode("utf-8")))


# s = base64.b64decode(bs)
# print(s)



# # hashlib
# import hashlib
# CENTOS = "centos6.3 centos4"
# md5 = hashlib.md5()
# md5.update(CENTOS.encode())
# print(CENTOS, " md5: ", md5.hexdigest())


# # regex
# import re
# p = r"(centos)\d+"
# m = re.match(p, CENTOS)
# print("group(0):", m.group(0))

# mi = re.finditer(p, CENTOS)
# for m in mi:
# 	print("group(0): ", m.group(0))


# urllib

#http://www.cnoil.com/investment/futures/
from urllib import request
url = "http://10.63.9.55/"
# url = "http://www.liaoxuefeng.com/"
# with request.urlopen(url) as f:
# 	data = f.read()
# 	print(data.decode("utf-8"))

# req = request.Request(url)
# req.add_header("content-type", "utf-8")
# with request.urlopen(req) as f:
# 	data = f.read()


from datetime import datetime
import time,threading
import json

# 1476758799
# 1476758573618 
# 1476758920226
def load_data():
	ts = int(time.time() * 1000)
	oic = "http://www.cnoil.com/index/yyzsDatas?codes=CONC_OILZ_DINIW_XAU_XAG&_=%s" % ts
	print("url:%s" % oic, flush = True)
	with request.urlopen(oic) as f:
		data = f.read()
		json_resule = data.decode("utf-8")


	d = json.loads(json_resule)
	return d

import sys

def thread_callback():
	i = 4
	while i > 0:
		print("开始时间：%s" % time.ctime())
		d = load_data()
		
		for l in d:
			print("%s\tname:%s,\topen:%s\theight:%s\tlow:%s" %
				 (l["QuoteTime"], l["Name"], l["Open"], l["Open"], l["Low"]), flush = True)

		time.sleep(3)
		# print(i)
		i = i - 1



import socket
# 114.215.194.241:9504
host = "114.215.194.241"
# host = "10.68.113.103"
# host = "www.baidu.com"
port = 9504
# port = 80
codeStr = ["CONC","OILZ", "DINIW", "XAU", "XAG"];    
msg = {'type': 'client',
		'code': codeStr,
		'crypt': '\u00002Z2\b7\u0002fR;\u000en\u0005dQ5Z1\u000b2\u0007oWq\u0001f\u0002gR(\u00011'};
msgJson = json.dumps(msg)
print(msgJson, flush = True)
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)      #定义socket类型，网络通信，TCP
# socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,"proxy01.cnooc",8080)
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
s.connect((host,port))
# s.send(msgJson.encode("utf-8"))
# data=s.recv(1024)
# print("socke:", data)
s.close()
print("connection ok")
# s.sendall("ok".code("utf-8"))
# data=s.recv(1024)
# print("socke:", data)

# java web socket impl
# https://github.com/TooTallNate/Java-WebSocket